<?php
/*
 * 小程序的一些api
 * @Date 2020-03-30
 * @Auther fujuhao
 */
namespace app\store\model;

use think\Model;
use think\db;
use think\Session;
// use app\common\library\wechat;
use think\Cache;

class Wxapi extends Model
{

	// 获取 APPID,APPSECRET
	public static function getConfig(){
		return Db::name('wxapp')->where('wxapp_id',10001)->find();
	}
	
	//http 请求
    public static function httpsRequest($url,$data = null){
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	    if (!empty($data)){
	        curl_setopt($curl, CURLOPT_POST, 1);
	        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	    }
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    $output = curl_exec($curl);
	    curl_close($curl);
	    return $output;
	}
	
	// 获取access_token
	public static function getAccessToken(){
		$cachekey = 'fujie_access_token';
		$access_token = Cache::get($cachekey);
		if(empty($access_token)){
			$wxapp	= self::getConfig();
			$api	= 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$wxapp['app_id'].'&secret='.$wxapp['app_secret'];
			$res = json_decode(self::httpsRequest($api));
			if(isset($res->access_token)){
				Cache::set($cachekey,$res->access_token,6000); // 7200
				return $res->access_token;
			}
			return $access_token;
		}
		return $access_token;
		
		
		// 当前目录绝对路径
		// $path	= $_SERVER['DOCUMENT_ROOT'].'/accesstoken.txt';
		// $data	= file_get_contents($path);
		// $wxapp	= self::getConfig();
		// $api	= 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$wxapp['app_id'].'&secret='.$wxapp['app_secret'];
		
		// $data = json_decode($data);
		
		// if(empty($data)||$data->expires_in <= time()){
		// 	$res = json_decode(self::httpsRequest($api));
		// 	if(isset($res->access_token)){
		// 		$res->expires_in = $res->expires_in + time() - 1000;
		// 		file_put_contents($path,json_encode($res));
		// 		return $res->access_token;
		// 	}
		// 	return $data->access_token;
		// }else{
		// 	return $data->access_token;
		// }

		
		// if( empty(Session::has('ACCESSTOKEN')) || (Session::get('ACCESSTOKEN_EXPIRESIN') <= time()) ){
		// 	$wxapp = self::getConfig();
		// 	$api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$wxapp['app_id'].'&secret='.$wxapp['app_secret'];
		// 	$res = json_decode(self::httpsRequest($api));
		// 	if(isset($res->access_token)){
		// 		Session::set('ACCESSTOKEN',$res->access_token);
		// 		// 减300 提前5分钟
		// 		Session::set('ACCESSTOKEN_EXPIRESIN',((time()+$res->expires_in)-500));
		// 		return $res->access_token;
		// 	}
		// 	return false;
		// }else{
		// 	return Session::get('ACCESSTOKEN');
		// }
	}
	
	/* 
	 * 订阅消息发送
	 * @Date 2020-03-30
	 * @Auther fujuhao
	 * @param $touser 用户的openid
	 * @param $template_id 公众号后台设置的订阅消息模板id
	 * @param $data 要推送的数据
	 * @param $page 用户收到消息后点击跳转的页面路径
	 */ 
	public static function sendSubscribeMessage($touser,$template_id,$data,$page=null){
		$access_token 	= self::getAccessToken(); // 是	接口调用凭证
		$params = [];
		$params['touser']			= $touser; // 是	接收者（用户）的 openid
		$params['template_id']		= $template_id; // 是	所需下发的订阅模板id
		$params['page'] 			= $page; // 否	点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
		$params['data'] 			= $data; // 是	模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
		$params['lang'] 			= 'zh_CN';
		$api						= 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
		$params 					= json_encode($params,JSON_UNESCAPED_UNICODE);
		// return $params;
		return self::httpsRequest($api,$params);
	}
	
	
	/**
	 * 砍价活动消息推送
	 * @param $taskIds 砍价活动表的ids [1,2,3]
	 *
	 */
	public static function bargain($taskIds){
		$year	= date("Y");
		$month	= date("m");
		$day	= date("d");
		$start	= mktime(0,0,0,$month,$day,$year);//当天开始00:00:00的时间戳
		$end	= mktime(23,59,59,$month,$day,$year);//当天结束23:59:59的时间戳
		
    	$data = Db::name('bargain_task')
    			->field('bt.*,u.open_id,g.goods_name')
    			// ->whereBetween('end_time',$start.','.$end)
    			// ->where('status','0')
    			->where('bt.task_id','in',$taskIds)
    			// ->where('bt.user_id',17172)
    			->alias('bt')
    			->join('user u','bt.user_id = u.user_id','LEFT')
    			->join('goods g','bt.goods_id = g.goods_id','LEFT')
    			->select();
    	
    	// return Wxapi::getAccessToken();
    	foreach ($data as $k=>$v){
    		$openid = $v['open_id'];
    		$tmplid = 'nKQzPZkV7v_yz3lStAvhXg7WYAQtPAnI7s77IktdxPI';
  
    		// 商品名称
    		$goods_name = (strlen($v['goods_name'])>20) ? (mb_substr($v['goods_name'],0,17,'UTF-8').'...') : $v['goods_name'];
    		
    		if($v['is_floor'] == 0){
    			// 砍价结果
    			$thing1 = '砍价失败';
    			// 砍价提示
    			$thing5 = '点击支付底价完成订单';
    		}
    		if($v['is_floor'] == 1){
    			$thing1 = '恭喜砍价成功';
    			$thing5 = '砍价失败';
    		}
    	
    		
    		$params = [];
    		$params['thing6'] = ['value'=>$goods_name];
    		$params['thing1'] = ['value'=>$thing1];
    		$params['amount3'] = ['value'=>'￥'.$v['actual_price'].'元'];
    		$params['thing5'] = ['value'=>$thing5];
    		
    		$page = '/pages/bargain/task/index?task_id='.$v['task_id'];
    		
    		// 发送订阅消息
    		$res = self::sendSubscribeMessage($openid,$tmplid,$params,$page);
    		
    		$txt = '砍价通知:'.$v['task_id'].json_encode($res).date('Y-m-d H:i:s',time())."\n";
    		file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
    		sleep(1); // 延迟1秒
    	}
	}
	
	/**
	 * 拼团失败消息推送
	 *
	 */
	public static function sharingFailed($list){
		foreach ($list as $k=>$v){
			// 模板id
			$tmplid = 'qdfkQryyWRr3iO95MZGcJu_ORo8gfFZd2f6gJwmFmQ0';
			$params = [];
			// 商品名称
			$goods_name = (strlen($v['goods']['goods_name'])>20) ? (mb_substr($v['goods']['goods_name'],0,17,'UTF-8').'...') : $v['goods']['goods_name'];
			$params['thing1'] = ['value'=>$goods_name];
			
			foreach($v['users'] as $u){
				// 用户的openid
				$openid = $u['user']['open_id'];
				// 拼团价
				$params['amount2'] = ['value'=>'￥'.$u['sharing_order']['pay_price'].'元'];
				// 退款金额
				$params['amount5'] = ['value'=>'￥'.$u['user']['pay_money'].'元'];
				// 失败原因
				$params['thing7'] = ['value'=>'拼团超时'];
				// 跳转地址
				$page = '/pages/user/index';
				$res = self::sendSubscribeMessage($openid,$tmplid,$params,$page);
				
				$txt = '拼团失败通知:'.$u['user_id'].json_encode($res).date('Y-m-d H:i:s',time())."\n";
    			file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
			}
			
		}
	}
	
	/**
	 * 拼团成功消息推送
	 *
	 */
	public static function sharingSuccess($list){
		// 模板id
		$tmplid = 'RuRNUQMrEmG1WnpqNY3Zu5AjGMAZJFKLLgrctm--NB4';
		$params = [];
		// 商品名称
		$goods_name = (strlen($list['goods']['goods_name'])>20) ? (mb_substr($list['goods']['goods_name'],0,17,'UTF-8').'...') : $list['goods']['goods_name'];
		$params['thing1'] = ['value'=>$goods_name];
		// 成团时间
		$params['date2'] = ['value'=>$list['end_time']['text']];
		
		// 整理拼团成员名称
		$nickname = [];
		foreach ($list['users'] as $v){
			$nickname[] = $v['user']['nickName'];
		}
		// 拼团成员名称
		$name = implode(',',$nickname);
		$params['thing3'] = ['value'=>(strlen($name)>20) ? (mb_substr($name,0,17,'UTF-8').'...') : $name];
		
		foreach($list['users'] as $v){
			// 拼团价格
			$params['amount5'] = ['value'=>'￥'.$v['sharing_order']['pay_price'].'元'];
			// 订单号
			$params['character_string6'] = ['value'=>$v['sharing_order']['order_no']];
			// 找出用户的openid
			$user = Db::name('user')->where('user_id',$v['user_id'])->find();
			// 跳转页面地址
			$page = '/pages/index/index';
			// 推送
			$res = self::sendSubscribeMessage($user['open_id'],$tmplid,$params,$page);
			// 记录日志
			$txt = '拼团成功通知:'.$v['user_id'].json_encode($res).date('Y-m-d H:i:s',time())."\n";
    		file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
		}
		
	}
	
	/**
	 * 活动通知
	 *
	 */
	public static function huodong($data){
		$params = [];
		$params['thing6'] = ['value'=>self::mbsubstr($data['title'])];
		$params['thing7'] = ['value'=>self::mbsubstr($data['content'])];
		$params['time11'] = ['value'=>self::mbsubstr($data['start'])];
		$params['thing10'] = ['value'=>self::mbsubstr($data['hint'])];
		$tmplid = $data['tmplid']; // 模板id
		$page   = $data['page']; // 跳转链接
		
		$arr = []; // 记录当前发送的情况
		$arr['send_times'] = 0;
		$arr['success_times'] = 0;
		foreach ($data['users'] as $v){
			$res = self::sendSubscribeMessage($v['open_id'],$tmplid,$params,$page);
			$res = json_decode($res);
			$arr['send_times'] = $arr['send_times'] + 1;
			if($res->errcode == 0) $arr['success_times'] = $arr['success_times'] + 1;
			// 记录日志
			$txt = '活动通知:'.$v['user_id'].json_encode($res).date('Y-m-d H:i:s',time())."\n";
    		file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
		}
		return $arr;
	}
	
	// 处理字符太长问题
	private static function mbsubstr($cont,$len=20){
		return (strlen($cont)>$len) ? (mb_substr($cont,0,($len-3),'UTF-8').'...') : $cont;
	}
}
?>